{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "K-Means Clustering - Overview\n",
    "=================================================\n",
    "\n",
    "## How do I discover natural groupings or segments in my data? \n",
    "  \n",
    "\n",
    "### Introduction\n",
    "\n",
    "Often we are given a large mass of data with no training labels.  That is, the data does not tell us what a \"good\" data item is and what a \"bad\" one is. So we have no prior idea what to look for.  In cases like these,  where we want to bootstrap our data exploration, to find some hook, some insight to get started,  looking for similar items or \"clusters\" is a well known approach.\n",
    "\n",
    "Clustering techniques operate on the attributes of our data and find \"clumps\" of data items that have attribute values that are close. One of the most common clustering techniques is \"K-Means Clustering\" which is simple to understand but powerful in impact.  It is also \"computationally hard\" from a theoretical point of view, i.e. as simple as it looks it can be demanding of computational resources and take time to converge to a solution.\n",
    "\n",
    "\n",
    "### Supervised and unsupervised learning\n",
    "\n",
    "K-Means Clustering is one of the many techniques that constitute \"unsupervised learning\".\n",
    "Before this we've looked at data that had some examples of good data and some of bad, or some examples of data that was classified in category A other in B, C, D and so on.  That is, we could learn from examples.  This mode of learning from examples is called \"supervised learning\" because you are given some prior training (\"supervision\") of how to proceed.   Most often in supervised learning one creates a model that fits the training data and then uses the model to predict over an unknown data set.\n",
    "\n",
    "Quite often no such prior knowledge (training data) exists and we are just given a data set and told - \"go extract some insights\".  This mode, where we have to find patterns in data without guidance of prior knowledge, is called \"unsupervised learning\". There is no \"supervision\" in the form of examples of good classification.  So we have to dive in and dig out *some* nugget(s) of wisdom, no matter what, to get started.\n",
    "\n",
    "K-Means Clustering is our \"power excavator\" to clear out the \"\"data underbrush\" and *then* lay the foundation of our grand data analysis edifice.\n",
    "\n",
    "\n",
    "### What is it and how does it work?\n",
    "\n",
    "What is K-Means Clustering?  First of all the name - it is called so because it operates by computing the \"mean\" of some attributes. That \"mean\" then becomes the center of one cluster. There are a small number, K, of such clusters. That is, the technique consists of computing \"K number of means\" leading to \"clustering\" of the data, around these \"K means\".\n",
    "\n",
    "How do we choose this K?  If we have some idea of what we are looking for or how many clsuters we expect or want, then we set K to be that number before we start the engines and let the algorithm rev along.\n",
    "\n",
    "If we don't know how many there are then our exploration will take a little longer and involve some trial and error as we try say K=3,4,5 until we see that the clusters are making some sense to us in our domain.  \n",
    "\n",
    "The K-Means algorithm is iterative. It starts by choosing K points at random from the data and use these as \"cluster centers\" just to get started. Then it at each step it decides which cluster to assign a point to based on which cluster center is closest.\n",
    "\n",
    "Once that is done it we have a new arrangement of points and so the \"center\" or \"mean\" of the cluster\" is computed again because it will have most probably shifted.   When does it not shift?  When we have a stable clustering. That is when we have iterated till we get no benefit from iterating further then that is our result.\n",
    "\n",
    "There are conditions under which K-Means does not converge i.e. there are no stable clusters but we won't get into that here. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A simple example\n",
    "\n",
    "Let's look at a well known public data set the 'iris' data set and see how irises cluster according to their properties.  This is just an example and we'll do this with a real world data set a little later.  There are three species named 'setosa'(in blue), 'virginica'(in green) and 'versicolor'(in red) represented in the scatter plot below.\n",
    "\n",
    "We are looking at two distinguishing characteristics, Sepal Length and Petal Length and plotting these."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Populating the interactive namespace from numpy and matplotlib\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEPCAYAAABBUX+lAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3XuUHOV55/HvgzSyhEaIYBAcL5KxhSArySeRL9gyvowx\nC8zEZrO7gO2g+BKk3bUjRJL12o6VrMTJcXxJvBtAsTdHOSb2ClgD64vYlYSN7SE2YINB3HGCsDHC\n3AYIQsIMI4ln/6hqTU9Pd9fb3VXV1V2/zzl1Zrqqut63C/tRz1NPPWXujoiI9L/Duj0BERHJhwK+\niEhJKOCLiJSEAr6ISEko4IuIl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+ycz+1sz\neweAmQ0QdTD8D+7+RuBy4DPxexyYE3fp/BjwlXj9A0T95F8PbAD+stXJmNnRwHrg3e7+BuB2ogfm\nVMYdi9d/Gfh4vH4DcIO7LydqeLYo3veTRH3YV7j7J4g6Hq4ALgKWAq81s1NbnaNIM0rpSGG5+wtm\n9gbg7cC7gK+b2aeIAu0yol77ADOI+oVXXBW//4dmdoSZHQHMB75mZicSBdyBNqb0FqJgfHM87izg\n5qrt34h/3gH8+/j3U4HfjedzvZn9S7y+XgvuW939MQAzu5OoLe5NbcxTpC4FfCk0d38ZuBG40czu\nAT5EFPDvc/faVrHN/AXwPXf/d2b2amC0zSl9191/r8G2l+KfB5n6/63QJye9VPV77TFEOqaUjhSW\nmZ1kZkuqVq0AHgb+CTgmbgeLmQ3Y1CcSvS9e/zaidrHPA0cw+VdAux0afwKcatGDKTCzuTXzq+cm\n4Lx4/zOILtYC7AXmtTkPkbYo4EuRDQL/YGb3mdldwG8CG+OLuOcAn49THzuBlVXvGzezO4AvARfE\n674AfDZeP4OpTwWq1zLWgXeb2e7KArwW+DBwVTyfm4GTG7y3csyLgTPiv07OAZ4A9rr7M8BN8YXl\nz9e8p9m8RNqm9sjSV8zsB8B/cfc7uj0XOPQYvYPufjAuM/3b+MKxSO6UIxTJ1iLgajM7DJig6oEb\nInnTN3wRkZJQDl9EpCQU8EVESkIBX0SkJBTwRURKQgFfRKQkFPBFREri/wNrW4EmNf0JXgAAAABJ\nRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x109dcc290>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%pylab inline\n",
    "import pandas as pd\n",
    "import matplotlib.pylab as plt\n",
    "\n",
    "df = pd.read_csv('../datasets/iris.csv')\n",
    "\n",
    "setosa = df[df.Species=='Iris-setosa']\n",
    "versicolor = df[df.Species=='Iris-versicolor']\n",
    "virginica = df[df.Species=='Iris-virginica']\n",
    "\n",
    "s = plot(setosa['SepalLength'],setosa['PetalLength'],'bo')\n",
    "vi = plot(virginica['SepalLength'],virginica['PetalLength'],'go')\n",
    "ve = plot(versicolor['SepalLength'],versicolor['PetalLength'],'ro')\n",
    "lx = ve[0].axes.set_xlabel('Sepal Length')\n",
    "ly = ve[0].axes.set_ylabel('Petal Length')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we see how data points cluster together when they have similarities.  We use this as an illustration because we knew beforehand that the data had three species of iris, and naturally we expect that their properties will be similar so they will show up as clusters.  But when we don't know in advance what the underlying data set looks like - we need to be able to explore and look for such clusters, although we may not know of these beforehand. Secondly, the data might cluster according to some properties but not according to others."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise\n",
    "Look up the Iris Data set, which is well known in data science circles as a toy example data set.  Then run the above code segment on different attributes than Petal Length and Sepal Length.  \n",
    "  \n",
    "How does the clustering vary?  \n",
    "  \n",
    "Can you see how picking the variables on which to cluster is an exploratory exercise and there is no a-priori set that stands out automatically or algorithmically?  \n",
    "  \n",
    "Does domain knowledge, i.e. knowing what flowers are and knowing their characteristics, help in picking the attributes on which to cluster?  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### Applications\n",
    "\n",
    "So how does K-Means Clustering help us in understanding our data better and where is it most useful?  \n",
    "\n",
    "First of all, we know this technique is useful in initial exploration of data when we have no training samples. But that's too general.  \n",
    "\n",
    "More specifically here are a few examples of usage but these are not the only ones and certainly not the most definitive ones.\n",
    "\n",
    "* Disambiguation of terms in a text corpus - how do we know if \"jaguar\" refers to a car or an animal?  The other words \"near\" jaguar can tell us, i.e. if the words in the same cluster as jaguar are \"leopard\",\"habitat\",\"prey\"  vs \"mileage\",\"f type\", \"luxury\" we know what the word refers to in this context. Or more importantly whether the document in which this term occurs is about cars or animals.  So document clustering is the overall application area.\n",
    "\n",
    "* Customer demographics.  Clustering customer data can tell us whether there are patterns in purchasing and then we can drill down into the clusters by building predictive models inside each cluster e.g. using multivariate linear regression\n",
    "\n",
    "* Political categories like the famous \"soccer moms\" coud be discovered using K-Means clustering.\n",
    "\n",
    "But once again, this technique is used for initial exploration when training samples are not available.\n",
    "\n",
    "We are going to apply K-Means to a data set from the UN on economic and demographic data for different countries, and use some well known techniques to find a \"good\" K to use.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>\n",
       "    @font-face {\n",
       "        font-family: \"Computer Modern\";\n",
       "        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');\n",
       "    }\n",
       "    div.cell{\n",
       "        width:800px;\n",
       "        margin-left:auto;\n",
       "        margin-right:auto;\n",
       "    }\n",
       "    h1 {\n",
       "        font-family: \"Charis SIL\", Palatino, serif;\n",
       "    }\n",
       "    h4{\n",
       "        margin-top:12px;\n",
       "        margin-bottom: 3px;\n",
       "       }\n",
       "    div.text_cell_render{\n",
       "        font-family: Computer Modern, \"Helvetica Neue\", Arial, Helvetica, Geneva, sans-serif;\n",
       "        line-height: 145%;\n",
       "        font-size: 120%;\n",
       "        width:800px;\n",
       "        margin-left:auto;\n",
       "        margin-right:auto;\n",
       "    }\n",
       "    .CodeMirror{\n",
       "            font-family: \"Source Code Pro\", source-code-pro,Consolas, monospace;\n",
       "    }\n",
       "    .prompt{\n",
       "        display: None;\n",
       "    }\n",
       "    .text_cell_render h5 {\n",
       "        font-weight: 300;\n",
       "        font-size: 16pt;\n",
       "        color: #4057A1;\n",
       "        font-style: italic;\n",
       "        margin-bottom: .5em;\n",
       "        margin-top: 0.5em;\n",
       "        display: block;\n",
       "    }\n",
       "    \n",
       "    .warning{\n",
       "        color: rgb( 240, 20, 20 )\n",
       "        }\n",
       "</style>\n",
       "<script>\n",
       "    MathJax.Hub.Config({\n",
       "                        TeX: {\n",
       "                           extensions: [\"AMSmath.js\"]\n",
       "                           },\n",
       "                tex2jax: {\n",
       "                    inlineMath: [ ['$','$'], [\"\\\\(\",\"\\\\)\"] ],\n",
       "                    displayMath: [ ['$$','$$'], [\"\\\\[\",\"\\\\]\"] ]\n",
       "                },\n",
       "                displayAlign: 'center', // Change this to 'center' to center equations.\n",
       "                \"HTML-CSS\": {\n",
       "                    styles: {'.MathJax_Display': {\"margin\": 4}}\n",
       "                }\n",
       "        });\n",
       "</script>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML at 0x10ad63350>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.core.display import HTML\n",
    "def css_styling():\n",
    "    styles = open(\"../styles/custom.css\", \"r\").read()\n",
    "    return HTML(styles)\n",
    "css_styling()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
